<template>
	<div class="zs-table-page-container">
		<div class="zs-card-sm zs-space-bottom zs-layout-flex-row zs-layout-justify-between">
			<div>
				<el-select v-model="searchObj.inspectionType" filterable clearable class="zs-select-md zs-space-right-sm" placeholder="类型" @change="queryList">
					<el-option v-for="item in inspectionTypeList" :key="item.id" :label="item.dicName" :value="item.id" />
				</el-select>
				<el-input v-model="searchObj.routeName" class="zs-select-md zs-space-right-sm" placeholder="路线名称" clearable />
				<el-select v-model="searchObj.status" filterable clearable class="zs-select-md zs-space-right-sm" placeholder="状态" @change="queryList">
					<el-option v-for="item in dictObj.INSPECTION_PROCESS_INSTANCE_STATUS" :key="item.id" :label="item.dictLabel" :value="item.dictValue" />
				</el-select>
				<el-popover popper-class="zs-popper" placement="bottom-end" trigger="click">
					<template #reference>
						<el-button class="zs-btn-square-solid" :class="{ 'zs-btn-square-solid-active': searchObj.cycleDayRule || searchObj.queryTime }">
							<el-icon>
								<MoreFilled />
							</el-icon>
						</el-button>
					</template>
					<template #default>
						<el-select v-model="searchObj.cycleDayRule" filterable clearable class="zs-select-md zs-space-right-sm" placeholder="触发方式" @change="queryList" :teleported="false">
							<el-option v-for="item in dictObj.CYCLE_DAY_RULE" :key="item.id" :label="item.dictLabel" :value="item.dictValue" />
						</el-select>
						<el-date-picker v-model="searchObj.queryTime" class="zs-space-right-sm" :type="activeTab" placeholder="开始日期" value-format="YYYY-MM-DD" :teleported="false" :clearable="false" :disabled-date="disabledDate" />
					</template>
				</el-popover>
				<el-button class="zs-btn-plain" @click="queryList"> 查询 </el-button>
			</div>
			<div class="zs-layout-flex-row zs-layout-items-center">
				<el-button :class="activeTab == 'date' ? 'zs-btn-primary' : 'zs-btn-info'" @click="tabChange('date')">按日</el-button>
				<el-button class="zs-space-left-sm" :class="activeTab == 'month' ? 'zs-btn-primary' : 'zs-btn-info'" @click="tabChange('month')">按月</el-button>
				<el-button class="zs-btn-plain zs-space-left-sm" @click="exportFn">
					<el-icon class="el-icon--left"> <Upload /> </el-icon>导出
				</el-button>
			</div>
		</div>

		<!-- teble -->
		<div class="zs-card zs-table-page-content">
			<el-table class="zs-table-page-main zs-table-first-row-special" :data="tableData.data" v-loading="tableData.loading" stripe>
				<el-table-column label="序号" width="60" align="center">
					<template #default="scope">
						<span v-if="scope.$index == 0">总计</span>
						<span v-else>{{ scope.$index + (tableData.currentPage - 1) * curPageSize }}</span>
					</template>
				</el-table-column>
				<!-- <el-table-column v-if="activeTab == 'month'" prop="queryTime" label="巡检时间" show-overflow-tooltip min-width="90" align="center" :formatter="defaultTableData" /> -->
				<el-table-column prop="inspectionTypeName" label="类型" show-overflow-tooltip align="center" :formatter="defaultTableData" />
				<el-table-column prop="routeName" label="路线名称" minWidth="120" show-overflow-tooltip align="left" :formatter="defaultTableData" />
				<el-table-column prop="roleName" label="角色名称" minWidth="120" show-overflow-tooltip align="left" :formatter="defaultTableData" />
				<el-table-column prop="mandatorySequenceName" label="强制顺序" show-overflow-tooltip align="center" :formatter="defaultTableData" />
				<el-table-column prop="cycleDayRuleName" label="触发方式" show-overflow-tooltip align="center" :formatter="defaultTableData" />
				<el-table-column prop="pointNum" label="点位个数" show-overflow-tooltip align="right" :formatter="defaultTableData" width="90" />
				<el-table-column label="状态" show-overflow-tooltip align="center">
					<template #default="scope">
						<span :class="{ 'zs-text-green ': scope.row?.status == 5, 'zs-text-red ': scope.row?.status == 99 }">{{ scope.$index == 0 ? '' : scope.row.statusName || '-' }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="rateOfCompletion" label="完成率" show-overflow-tooltip align="right" :formatter="defaultTableData" />
				<el-table-column prop="createTime" label="开始时间" show-overflow-tooltip min-width="120" align="center" :formatter="defaultTableData" />
				<el-table-column prop="planCompleteTime" label="计划完成时间" show-overflow-tooltip align="center" minWidth="120" :formatter="defaultTableData" />
				<el-table-column prop="completeTime" label="实际完成时间" show-overflow-tooltip align="center" minWidth="120" :formatter="defaultTableData" />
				<el-table-column label="操作" min-width="90" align="center">
					<template #default="scope">
						<el-button v-if="scope.$index > 0" class="zs-link" link size="small" @click="goInfo(scope.row)">查看</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div class="zs-space-top-sm zs-table-page-pagination">
				<el-pagination v-model:currentPage="tableData.currentPage" v-model:page-size="curPageSize" :page-sizes="curPageSizes" :small="true" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="tableData.total" @size-change="pageChange('size', $event)" @current-change="pageChange('page', $event)" />
			</div>
		</div>
	</div>
</template>

<script setup>
	import { ref, reactive } from 'vue';
	import { parseTime, downloadNewFile } from '@/utils/publicUtils';
	import { useStore } from 'vuex';
	import { useRoute, useRouter } from 'vue-router';
	import detailApi from '@/api/Manage/Business/detailPages';
	import { getPropertyDictoryApi } from '@/api/dbPublic.js';

	const store = useStore();
	const curPageSizes = ref(store.state.uiPageSizes);
	const curPageSize = ref(store.state.uiPageSizeDefault);
	const router = useRouter();
	const routeQuery = useRoute().query;
	const projectName = ref(decodeURI(routeQuery.projectName));
	let dictObj = store.getters.getDictObj(['INSPECTION_PROCESS_INSTANCE_STATUS', 'CYCLE_DAY_RULE']);

	//查询条件
	let searchObj = reactive({ pageNumber: 1, pageSize: curPageSize.value, projectCode: routeQuery.projectCode, queryTime: routeQuery.queryTime });

	// 列表 filed
	let tableData = reactive({
		currentPage: 1,
		total: 0,
		loading: false,
		data: [],
	});

	// 列表数据源
	const queryList = async () => {
		tableData.loading = true;
		searchObj.queryTimeFlag = activeTab.value == 'date' ? 1 : 2;
		if (activeTab.value == 'month') {
			let lastDay = getLastDayOfMonth(searchObj.queryTime);
			searchObj.queryTime = lastDay;
		}
		let res = await detailApi.inspectionRouteDetailListApi(searchObj);
		if (res.data.code !== 200) return;
		initData(res.data.data.list);
		if (res.data.data.list.length > 0) {
			res.data.data.list.unshift(res.data.data.infoResp);
		}
		tableData.data = res.data.data.list || [];
		tableData.total = res.data.data.total || 0;
		tableData.loading = false;
	};

	const initData = list => {
		list.forEach(item => {
			item.createTime = item.createTime ? parseTime(item.createTime, '{y}-{m}-{d} {h}:{i}') : '-';
			item.planCompleteTime = item.planCompleteTime ? parseTime(item.planCompleteTime, '{y}-{m}-{d} {h}:{i}') : '-';
			item.completeTime = item.completeTime ? parseTime(item.completeTime, '{y}-{m}-{d} {h}:{i}') : '-';
		});
	};

	//校验时间
	const disabledDate = time => {
		return time.getTime() > new Date(routeQuery.queryTime).getTime();
	};

	//tab查询
	let activeTab = ref(routeQuery.tabType);
	const tabChange = type => {
		activeTab.value = type;
		if (type == 'date') {
			searchObj.queryTime = routeQuery.queryTime;
		}
		queryList();
	};

	//字典
	const inspectionTypeList = ref([]);
	const getDictory = async () => {
		let res = await getPropertyDictoryApi({ sort: true, delFalg: 0 });
		if (res.data.code !== 200) return;
		inspectionTypeList.value = res.data.data.INSPECTION_TYPE || [];
	};

	// 分页
	const pageChange = (type, size) => {
		if (type == 'size') {
			searchObj.pageSize = size;
		} else {
			searchObj.pageNumber = size;
		}
		queryList();
	};

	const goInfo = () => {
		router.push({
			path: '/page/routeController/index',
			query: {
				rid: 'page_query_inspection_route_detail_point_list',
				rTitle: '点位信息',
				projectCode: routeQuery.projectCode,
				queryTime: routeQuery.queryTime,
				activeTab: activeTab.value
			},
		});
	};

	// 导出
	const exportFn = async () => {
		const fileName = projectName.value + `巡检路线表.xls`;
		delete searchObj.pageNumber;
		delete searchObj.pageSize;
		let fileData = await detailApi.inspectionRouteExportApi(searchObj);
		downloadNewFile(fileData.data, fileName);
	};

	//取某月最后一天的日期
	const getLastDayOfMonth = date => {
		const currentDate = routeQuery.queryTime.split('-');
		const year = new Date(date).getFullYear();
		const month = new Date(date).getMonth();
		const lastDay = new Date(year, month + 1, 0);
		const formattedDate = `${lastDay.getFullYear()}-${String(lastDay.getMonth() + 1).padStart(2, '0')}-${String(lastDay.getDate()).padStart(2, '0')}`;
		return year == currentDate[0] && month == currentDate[1] - 1 ? routeQuery.queryTime : formattedDate;
	};

	const defaultTableData = (row, column, cellValue, index) => {
		let emptyVal = index == 0 ? '' : '-';
		return cellValue || cellValue === 0 ? cellValue : emptyVal;
	};

	getDictory();
	queryList();
</script>

<style scoped lang="scss">
	:deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
		background: #477afd;
	}
</style>
